package praktikumid.w07.p3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author Aleksandr
 *
 */

public class JSONParser {

	public static void main(String[] args) {
		
		JSONParser p = new JSONParser();
		p.getPanoramioPictures();

	}
	
	public List<String> getAuthors() {
		List<String> authors = new ArrayList<String>();
		
		String response = getPanoramioPictures();
		
		authors = parsePanoramioResponse(response);
		
		return authors;
	}
	
	public String getPanoramioPictures() {
		XMLParser p = new XMLParser();
		String panoramio_query = p.composePanoramioQuery("Tallinn");
		if(panoramio_query == null) {
			System.err.println("Failed to process GeocodeResponse.");
			return "";
		}
		System.out.println("Panoramio query: " + panoramio_query);
	
		String panoramio_response = getPanoramioResponse(panoramio_query);
		if(panoramio_response == null) {
			System.err.println("Failed to fetch Panoramio response.");
			return "";
		}
		System.out.println("Panoramio response: " + panoramio_response);
		return panoramio_response;
	}
	
	private String getPanoramioResponse(String query) {
		try {
			URL url = new URL(query);
			URLConnection conn = url.openConnection();
			BufferedReader br = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String inputline, output = "";
			while((inputline = br.readLine()) != null) {
				output += inputline;
			}
			br.close();
			if (output.length() > 0) 
				return output;
			else
				return null;
			// return (output.length() > 0) ? output : null;
		} catch (MalformedURLException e) {
			System.err.println("Malformed URL detected. Quitting.");
			return null;
		} catch (IOException e) {
			System.err.println("Connectivity problem detected. Quitting.");
			return null;
		}		
	}
	
	private List<String> parsePanoramioResponse(String response) {
		List<String> authors = new ArrayList<String>();
		Pattern p = Pattern.compile("\"owner_name\"\\s*:\\s*\"([A-z\\s-]+)\"");
		Matcher m = p.matcher(response);
		
		while (m.find())
		{
			String author = m.group(1);
			//System.out.println("Author: " + author);
			authors.add(author);
		}
		return authors;
	}

}
